package com.zhijian.medical.config;

import com.zhijian.medical.entity.CommonResult;
import com.zhijian.medical.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常返回处理
 *
 * @Author chengqing
 * @DateTime 2019年4月14日 下午3:33:53
 * @Version 1.0.1
 */
@SuppressWarnings("rawtypes")
@Slf4j
public class ResponseJsonExceptionHandler extends AbstractHandlerExceptionResolver implements InitializingBean {

    private HttpMessageConverter messageConverter;

    public ResponseJsonExceptionHandler(HttpMessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                              Exception ex) {
        CommonResult resp = CommonResult.error();
        log.error("ctrl exception", ex);
        if (ex instanceof IllegalArgumentException) {
            if (!"null".equalsIgnoreCase(ex.getMessage())) {
                // 非空异常，提示默认信息
                resp.setData(ex.getMessage());
            }
        } else if (ex instanceof BusinessException) {
            // 自定义异常,补充提示信息
            BusinessException exception = (BusinessException) ex;
            resp.setCode(exception.getExCode());
            resp.setMessage(exception.getExMsg());
            resp.setData(exception.getExInfo());
        }
        try {
            messageConverter.write(resp, MediaType.APPLICATION_JSON_UTF8, new ServletServerHttpResponse(response));
        } catch (HttpMessageNotWritableException | IOException e) {
            log.error(e.getMessage(), e);
        }
        return new ModelAndView();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (messageConverter == null) {
            throw new Exception("messageConverter is null");
        }
    }
}
